package com.tater.server;


import com.tater.codec.RpcDecoder;
import com.tater.codec.RpcEncoder;
import com.tater.codec.RpcRequest;
import com.tater.codec.RpcResponse;
import com.tater.handler.ServerHandler;
import com.tater.serializer.FASTJSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.InitializingBean;

import javax.annotation.PreDestroy;

public class NettyServer {
    private ServerHandler serverHandler;
 
    private EventLoopGroup boss;
    private EventLoopGroup worker;

    private Integer serverPort;
 
    public NettyServer(ServerHandler serverHandler, Integer serverPort) {
        this.serverHandler = serverHandler;
        this.serverPort = serverPort;
        regist("127.0.0.1");
        System.out.println("#############################Netty服务启动成功："+serverPort);

    }

    /**
     * 注册服务到zk
     * @param ip
     */
    private void regist(String ip) {

    }


    public void start() throws Exception {
        //负责处理客户端连接的线程池
        boss = new NioEventLoopGroup();
        //负责处理读写操作的线程池
        worker = new NioEventLoopGroup();
 
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boss, worker)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        //添加解码器
                        pipeline.addLast(new RpcEncoder(RpcResponse.class, new FASTJSONSerializer()));
                        //添加编码器
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new FASTJSONSerializer()));
                        //添加请求处理器
                        pipeline.addLast(serverHandler);
 
                    }
                });
        bind(serverBootstrap, serverPort);
    }
 
    /**
     * 如果端口绑定失败，端口数+1，重新绑定
     */
    public void bind(final ServerBootstrap serverBootstrap, int port) {
        serverBootstrap.bind(port);
    }
 
    @PreDestroy
    public void close() throws InterruptedException {
        boss.shutdownGracefully().sync();
        worker.shutdownGracefully().sync();
    }
}